package main

import (
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

type MQTTConfig struct {
	URI string
	Topic string
}

func NewMQTT(config MQTTConfig) (chan mqtt.Message, error) {
	ch := make(chan mqtt.Message)
	opts := mqtt.NewClientOptions().AddBroker(config.URI)
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		return ch, token.Error()
	}
	onMessageReceived := func(c mqtt.Client, message mqtt.Message) {
		ch <- message
	}
	if token := client.Subscribe(config.Topic, 0, onMessageReceived); token.Wait() && token.Error() != nil {
		return ch, token.Error()
	}
	return ch, nil
}
